var Game = function(images, runCallback){
    g = {
        keys : {},
        actions : {},
        keyDown : {},
        images : {},
        scene : null,
    }

    g.canvas = document.getElementById("canvas")
    g.ctx = canvas.getContext("2d") 

    g.registerActions = function(key, callback){
        g.actions[key] = callback
    }

    window.addEventListener("keydown", function(event){
        g.keyDown[event.code] = true
    })
    window.addEventListener("keyup", function(event){
        g.keyDown[event.code] = false
    })

    g.act = function(){
        keys = Object.keys(g.actions)
        for (var i = 0; i < keys.length; i ++){
            if (g.keyDown[keys[i]]){
                g.actions[keys[i]]()
            }
        }
    }

    g.drawImage = function(img){
        g.ctx.drawImage(img.img, img.x, img.y)
    }
    g.drawbg = function(img){
        g.ctx.drawImage(img.img, img.x, img.y, g.canvas.width, g.canvas.height)
    }

    g.update = function(){
        g.scene.update()
    } 
    g.draw = function(){
        g.scene.draw()
    }

    var runloop = function(){
        g.update()

        g.act()
        g.ctx.clearRect(0, 0, g.canvas.width, g.canvas.height)
        g.draw()
        
        setTimeout(function(){
            runloop()
        }, 1000/myUtils.fps)
    }

    //载入所有图片资源
    var loads = []
    var names = Object.keys(images)
    for (let i = 0; i < names.length; i++){
        let name = names[i]
        let img = new Image()
        img.src = images[name] 
        img.onload = function(){
            loads.push(1)
            g.images[name] = img
            if (loads.length == names.length){
                g.__start()
            }
        }

    }

    g.imgByName = function(name){
        var img = g.images[name]
        var image = {
            img : img,
            w : img.width,
            h : img.height,
        }
        return image
    }

    g.replaceScene = function(scene){
        g.scene = scene
    }

    g.runWithScene = function(scene){
        g.scene = scene
        setTimeout(function(){
            runloop()
        }, 1000/myUtils.fps)
    }
    // 开始游戏
    g.__start = function(){
        runCallback()
    }
    return g
}
